package com.nhim.cms.admin.client.contentmanagement.ui;

import java.util.ArrayList;
import java.util.List;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.HasKeyboardPagingPolicy.KeyboardPagingPolicy;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SingleSelectionModel;
import com.nhim.cms.admin.client.ScrollablePagerPanel;
import com.nhim.cms.admin.client.rpc.ContentTypeRPCService;
import com.nhim.cms.admin.client.rpc.ContentTypeRPCServiceAsync;
import com.nhim.cms.admin.shared.ContentTypeRPCProxy;

public class ContentTypeSelect extends PopupPanel {

	private static ContentTypeUiBinder uiBinder = GWT
			.create(ContentTypeUiBinder.class);

	@UiTemplate("ContentTypeSelect.ui.xml")
	interface ContentTypeUiBinder extends
			UiBinder<Widget, ContentTypeSelect> {
	}


	@UiField
	Button btnCancel;
	@UiField
	ScrollablePagerPanel contentTypeList;
	public ContentTypeSelect() {
		
		super(false, true);
		add(uiBinder.createAndBindUi(this));
		// Create a CellList.
		ContentTypeCell templateList = new ContentTypeCell();
		
		contentTypeCellList = new CellList<ContentTypeRPCProxy>(templateList,
				CONTENT_TYPE_KEY_PROVIDER);
		contentTypeCellList.setPageSize(30);
		contentTypeCellList.setKeyboardPagingPolicy(KeyboardPagingPolicy.INCREASE_RANGE);
		contentTypeCellList.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.BOUND_TO_SELECTION);
		contentTypeCellList.setSelectionModel(contentTypeSelectionModel);		
		contentTypeList.setDisplay(contentTypeCellList);
		contentTypeDataProvider.addDataDisplay(contentTypeCellList);
		bindContentType();
	}
	private final ContentTypeRPCServiceAsync service = GWT.create(ContentTypeRPCService.class);
	private void bindContentType() {
		
		final List<ContentTypeRPCProxy> data = contentTypeDataProvider.getList();
		service.findAll(new AsyncCallback<ArrayList<ContentTypeRPCProxy>>(){

			@Override
			public void onFailure(Throwable error) {
				Window.alert(error.getMessage());	
			}

			@Override
			public void onSuccess(ArrayList<ContentTypeRPCProxy> result) {
				for(ContentTypeRPCProxy proxy : result)
				{
					data.add(proxy);
				}				
			}});
	}
	/**
	 * The CellList.
	 */
	private CellList<ContentTypeRPCProxy> contentTypeCellList;
	// Add a selection model so we can select cells.
	SingleSelectionModel<ContentTypeRPCProxy> contentTypeSelectionModel = new SingleSelectionModel<ContentTypeRPCProxy>(
			CONTENT_TYPE_KEY_PROVIDER);
	/**
	 * The key provider that provides the unique ID of a contentType.
	 */
	public static final ProvidesKey<ContentTypeRPCProxy> CONTENT_TYPE_KEY_PROVIDER = new ProvidesKey<ContentTypeRPCProxy>() {
		public Object getKey(ContentTypeRPCProxy item) {
			return item == null ? null : item.getId();
		}
	};

	private ListDataProvider<ContentTypeRPCProxy> contentTypeDataProvider = new ListDataProvider<ContentTypeRPCProxy>();
	/**
	 * The Cell used to render a {@link GroupCell}.
	 */
	private class ContentTypeCell extends AbstractCell<ContentTypeRPCProxy> {

		public ContentTypeCell() {
			 super("keydown","dblclick");
		}
		 @Override
		    public void onBrowserEvent(Context context, Element parent, ContentTypeRPCProxy value,
		        NativeEvent event, ValueUpdater<ContentTypeRPCProxy> valueUpdater) {
		      // Check that the value is not null.
		      if (value == null) {
		        return;
		      }

		      // Call the super handler, which handlers the enter key.
		      super.onBrowserEvent(context, parent, value, event, valueUpdater);

		      // On click, perform the same action that we perform on enter.
		      if ("dblclick".equals(event.getType())) {
		        this.onEnterKeyDown(context, parent, value, event, valueUpdater);
		      }
		    }
		 @Override
		    protected void onEnterKeyDown(Context context, Element parent,
		    		ContentTypeRPCProxy value, NativeEvent event, ValueUpdater<ContentTypeRPCProxy> valueUpdater) {
		      if(listener != null)
		      {
		    	  hideMe();
		    	  listener.onContentTypeSelected(value);
		    	  
		      }
		    }

		@Override
		public void render(com.google.gwt.cell.client.Cell.Context arg0,
				ContentTypeRPCProxy value, SafeHtmlBuilder sb) {

			// Value can be null, so do a null check..
			if (value == null) {
				return;
			}

			sb.appendHtmlConstant("<table>");

			// Add the content type image.
			sb.appendHtmlConstant("<tr>");

			// Add the name and description.
			sb.appendHtmlConstant("<td style='font-size:95%;'>");
			sb.appendEscaped(value.getName());
			sb.appendHtmlConstant("</td></tr></table>");
		}

	}
	private void hideMe()
	{
		this.hide();
	}
	
	private Listener listener;

	/**
	 * Custom listener for this widget.
	 */
	public interface Listener {

		/**
		 * Called when the user save Template
		 * 
		 */
		void onContentTypeSelected(ContentTypeRPCProxy proxy);
	}

	public void setListener(Listener listener) {
		this.listener = listener;
	}
	@UiHandler("btnCancel")
	void handleButtonCancelClick(ClickEvent e) {
		this.hide();

	}

}
